/**
 *  每小时更新一次，如果token失效，重新获取token 再次发起每小时更新一次;
 */
import axios from "axios";
import {config} from "../config/config";
import {GamesModel} from "../models/gamesModel";
import logger from "../logger";

require('express-async-errors')

export async function getToken(appid: string, secret: string) {
    const db_data: any = await GamesModel.findOne({appid: appid});
    if (!db_data.token || !db_data.token.access_token) {
        return await getNewToken(appid, secret);
    } else {
        return db_data.token;
    }
}

export async function getNewToken(appid: string, secret: string) {
    const token: any = await axios.post(config.getAccessToken, {
        appid: appid,
        secret: secret,
        grant_type: 'client_credential'
    })
    if (token.data.err_no === 0) {
        await GamesModel.updateOne({appid: appid}, {$set: {token: token.data.data}});
        return token.data.data;
    } else {
        logger.error({msg: `get new toke err ${appid}`, data: token.data});
        return null;
    }
}

export async function startUpdateToken() {
    const games: any[] = await GamesModel.find();
    for (const item of games) {
        await getNewToken(item.appid, item.secret);
    }
    return games;
}